package com.apobates.forum.trident.event;

import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import com.apobates.forum.core.api.dao.PostsDescriptorDao;
import com.apobates.forum.core.entity.Posts;
import com.apobates.forum.core.entity.PostsDescriptor;
import com.apobates.forum.core.impl.event.PostsPublishEvent;
import com.apobates.forum.utils.ip.IPMatcher;
import com.apobates.forum.utils.ip.IPMatcher.IpMatchResult;
import eu.bitwalker.useragentutils.UserAgent;
/**
 * 回复操作描述记录
 * 
 * @author xiaofanku
 *
 */
public class PostsDescriptorRecordListener implements ApplicationListener<PostsPublishEvent>{
	@Autowired
	private PostsDescriptorDao postsDescriptorDao;
	private final static Logger logger = LoggerFactory.getLogger(PostsDescriptorRecordListener.class);
	
	@Override
	public void onApplicationEvent(PostsPublishEvent event) {
		logger.info("[Event][Posts][3]回复动作描述处理开始");
		Posts p = event.getPosts();
		PostsDescriptor pd = new PostsDescriptor();
		pd.setMemberId(p.getMemberId());
		pd.setMemberNames("*");
		pd.setMemberNickname(p.getMemberNickname());
		pd.setIpAddr(p.getIpAddr());
		pd.setPostsId(p.getId());
		//
		pd.setAgent(event.getUserAgent());
		pd.setDevice(UserAgent.parseUserAgentString(event.getUserAgent()).getOperatingSystem().getName());
		//
		Optional<IpMatchResult> mr = IPMatcher.getInstance().matchToResult(p.getIpAddr());
		if(mr.isPresent()){
			IpMatchResult imr = mr.get();
			pd.setCity(imr.getCity());
			pd.setProvince(imr.getProvince());
			pd.setDistrict(imr.getDistrict());
			pd.setIsp(imr.getIsp());
		}
		postsDescriptorDao.save(pd);
		logger.info("[Event][Posts][3]回复动作描述处理开始");
	}
}
